package com.sdtele.tta.operation;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.sdtele.tta.dac.Dac;
import com.sdtele.tta.models.JsonRequest;
import com.sdtele.tta.models.JsonResponse;
import com.sdtele.tta.models.Team;
import com.sdtele.tta.models.User;
import com.sdtele.tta.utils.TeamUtils;

/**
 * 操作类实现：GetUser(json.operation=getUser)
 * 
 * @author XCream
 */
public class OperationDelTeam extends Operation {

	@Override
	public JsonResponse handle(JsonRequest jsonRequest) {
		JsonResponse jres = new JsonResponse();
		User curUser = (User) request.getSession().getAttribute("user");
		if (curUser!=null) {
			long id = jsonRequest.getJsonObject().get("teamId").getAsLong();
			Team team = Dac.getInstance().getTeam(id);
			if (curUser.getIsManager() == 1) {
				Set<Long> teamIdSet = new HashSet<Long>();
				// teamIdSet.add(curUser.getTeamId());
				TeamUtils.teamAuthority(curUser.getTeamId(), teamIdSet);
				if (!teamIdSet.contains(team.getId())) {
					jres.setStatus(1);
					jres.setMessage("您的管理权限不够删除该组织");
				} else {
					List<Team> subTeams = Dac.getInstance().getsubTeams(id);
					if (subTeams!=null) {
						Set<String> teamNameSet = new HashSet<String>();
						TeamUtils.teamAuthorityByTeamName(id, teamNameSet);						
						jres.setStatus(1);
						jres.setMessage("该组织下有子组织，不能删除");
						jres.setEntity(teamNameSet);
					} else {
						List<User> userList = Dac.getInstance().getUserbyteamId(id);
						if (userList!=null) {
							jres.setStatus(1);
							jres.setMessage("该组织下有人员，请先删除人员");
						} else {
							if (Dac.getInstance().delTeam(id)) {
								jres.setStatus(0);
								jres.setMessage("删除组织成功");
							} else {
								jres.setStatus(1);
								jres.setMessage("删除组织失败");
							}
						}
					}
				}
			} else {
				jres.setStatus(1);
				jres.setMessage("您不是管理员，没有权限删除组织");
			}
		} else {
			jres.setStatus(1);
			jres.setMessage("用户未登录");
		}
		return jres;
	}

}
